
<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>发票录入列表查询</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 搜索筛选 -->
    <el-form :inline="true" :model="formInline" class="models-search">

      <el-form-item label="报销人：">
        <el-input size="small" v-model="formInline.baoxiaoname" placeholder="输入报销人"></el-input>
      </el-form-item>
      <el-form-item label="发票号：">
        <el-input size="small" v-model="formInline.billnum" placeholder="输入发票号"></el-input>
      </el-form-item>

      <el-form-item>
        <el-button size="small" type="primary" icon="el-icon-search" @click="search">搜索</el-button>
        <el-button size="small" type="primary" icon="el-icon-plus" @click="handleEdit">添加</el-button>
      </el-form-item>
      <el-form-item v-for="(item, index) in TagList" :key="index">
        <el-button size="small" type="success" icon="el-icon-circle-plus-outline" @click="handleButtonClick(item)">{{ item.modelTag }}</el-button>
      </el-form-item>
    </el-form>
    <!-- 标签选择器 -->

    <el-tag
      :key="index"
      v-for="(item, index) in TagClickList"
      closable
      :disable-transitions="false"
      @close="handleClose(item)">
      {{item.modelTag}}
    </el-tag>

    <!--列表-->
    <el-table  :data="listData" highlight-current-row v-loading="loading"  element-loading-text="拼命加载中" style="width: 100%;">
      <el-table-column align="center" type="selection" width="60">
      </el-table-column>
      <el-table-column sortable prop="bid" label="发票id" width="100">
      </el-table-column>
      <el-table-column sortable prop="billnum" label="发票号" width="150">
      </el-table-column>
      <el-table-column sortable prop="baoxiaoname" label="报销人" width="250">
      </el-table-column>
      <el-table-column sortable prop="username" label="处理人" width="200">
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <Pagination v-bind:child-msg="pageparm" @callFather="callFather"></Pagination>
    <!-- 编辑界面 -->
<!--    <el-dialog :title="title" :visible.sync="editFormVisible" width="30%" @click='closeDialog("edit")'>-->
<!--      <el-form label-width="120px" :model="editForm" ref="editForm" :rules="rules">-->
<!--        <el-form-item label="发票号" prop="billnum">-->
<!--          <el-input size="small" v-model="editForm.billnum" auto-complete="off" placeholder="请输入发票号"></el-input>-->
<!--          <imageUpload v-model="fileList" @dataFromChild="handleChildData" />-->
<!--        </el-form-item>-->

<!--        <el-form-item label="报销人" prop="baoxiaoname">-->
<!--          <el-input size="small" v-model="editForm.baoxiaoname" auto-complete="off" placeholder="请输入报销人"></el-input>-->
<!--        </el-form-item>-->
<!--        <el-form-item label="报销金额" prop="amount">-->
<!--          <el-input size="small" v-model="editForm.amount" auto-complete="off" placeholder="请输入报销金额"></el-input>-->
<!--        </el-form-item>-->
<!--      </el-form>-->
<!--      <div slot="footer" class="dialog-footer">-->
<!--        <el-button size="small" @click='closeDialog("edit")'>取消</el-button>-->
<!--        <el-button size="small" type="primary" :loading="loading" class="title" @click="submitForm('editForm')">保存</el-button>-->
<!--      </div>-->
<!--    </el-dialog>-->
<!--    <el-dialog v-dialog-drag :modal-append-to-body="false" :visible.sync="imgVisible" width="30%">-->
<!--      <img width="100%" :src="dialogImageUrl" alt="图片未找到"/>-->
<!--    </el-dialog>-->
  </div>
</template>

<script>
import {
  ModelgetByModelTagId,
  FapiaoList, FapiaoSave, fapiaoPicUplod
} from '../../api/userMG'
import Pagination from '../../components/Pagination'
import imageUpload from '../../imageUpload/index.vue'

export default {
  data() {
    return {
      imgVisible: false,
      dialogImageUrl: undefined,
      nshow: true, //switch开启
      fshow: false, //switch关闭
      loading: false, //是显示加载
      editFormVisible: false, //控制编辑页面显示与隐藏
      menuAccessshow: false, //控制数据权限显示与隐藏
      title: '添加',
      imageUrl: '',
      fileList: [], // 用于存储文件信息的数组
      editForm: {
        id: '',
        baoxiaoname:'',
        billnum:'',
        amount:'',
      },
      // rules 表单验证
      rules: {
        baoxiaoname: [
          { required: true, message: '请输入报销人', trigger: 'blur' }
        ],
        billnum: [
          { required: true, message: '请输入发票号', trigger: 'blur' }
        ],
        amount: [
          { required: true, message: '请输入报销金额', trigger: 'blur' }
        ],

      },
      formInline: {
        pageNum: 1,
        pageSize: 10,
        baoxiaoname:'',
        billnum:'',
        username:''
      },
      // 删除
      seletedata: {
        ids: '',
        token: localStorage.getItem('logintoken')
      },
      userparm: [], //搜索权限
      listData: [], //模型
      TagList:[],//所有tag列表
      TagClickList:new Set(),//选择的tag列表
      // 数据权限
      RoleRight: [],
      RoleRightProps: {
        children: 'children',
        label: 'name'
      },
      // 选中
      checkmenu: [],
      //参数role
      saveroleId: '',
      // 分页参数
      pageparm: {
        currentPage: 1,
        pageSize: 10,
        total: 1
      }
    }
  },
  // 注册组件
  components: {
    Pagination,
    imageUpload
  },
  /**
   * 数据发生改变
   */

  watch: {
  },
  /**
   * 创建完毕
   */

  created() {
    this.getdata(this.formInline)
  },

  /**
   * 里面的方法只有被调用才会执行
   */

  methods: {
    handleClose(item) {
      this.TagClickList.delete(item);
      // 强制更新视图
      this.$set(this, 'TagClickList', new Set(this.TagClickList));
      if(this.TagClickList.size==0){
        this.getdata(this.formInline)
      }else{
        this.updateListData()
        console.log(this.TagClickList)
      }
    },

    addParam() {
      this.editForm.reqParamKeys.push('');
      this.editForm.reqParamValues.push('');
    },
    deleteParam(key) {
      const index = this.editForm.reqParamKeys.indexOf(key);
      if (index !== -1) {
        this.editForm.reqParamKeys.splice(index, 1);
        this.editForm.reqParamValues.splice(index, 1);
      }
    },


    // 获取模型列表
    getdata(parameter) {
      /***
       * 调用接口，注释上面模拟数据 取消下面注释
       */
      // ModelTagAllList()
      //   .then(res => {
      //     if (res.code==200) {
      //       this.loading = false
      //       this.TagList = res.data
      //     }
      //   })
      //   .catch(err => {
      //     this.loading = false
      //     this.$message.error('获取Tag信息失败，请稍后再试！')
      //   })

      FapiaoList(parameter)
        .then(res => {
          this.loading = false
          if (res.code!=0) {
            this.$message({
              type: 'info',
              message: res.msg
            })
          } else {
            this.loading = false
            this.listData = res.data.records
            // 分页赋值
            this.pageparm.currentPage = this.formInline.current
            this.pageparm.pageSize = this.formInline.size
            this.pageparm.total = res.data.total
          }
        })
        .catch(err => {
          this.loading = false
          this.$message.error('获取列表失败，请稍后再试！')
        })
    },
    // 分页插件事件
    callFather(parm) {
      console.log(parm)
      this.formInline.pageNum = parm.currentPage
      this.formInline.pageSize = parm.pageSize
      this.formInline.baoxiaoname = typeof(this.formInline.baoxiaoname)==='undefined'?'':this.formInline.baoxiaoname
      this.formInline.billnum = typeof(this.formInline.billnum)==='undefined'?'':this.formInline.billnum
      this.getdata(this.formInline)

    },
    // 搜索事件
    search() {
      this.formInline.baoxiaoname = typeof(this.formInline.baoxiaoname)==='undefined'?'':this.formInline.baoxiaoname
      this.formInline.billnum = typeof(this.formInline.billnum)==='undefined'?'':this.formInline.billnum
      this.getdata(this.formInline)
    },
    //显示编辑界面
    handleEdit: function(index, row) {
      // this.editFormVisible = true
      if (row != undefined && row != 'undefined') {
        this.title = '修改'
        this.editForm.id=row.id
        this.editForm.baoxiaoname = row.baoxiaoname
        this.editForm.billnum = row.billnum
        this.editForm.amount = row.amount

      } else {
        this.$router.push({ name: 'fapiaoedit' });//跳转到添加界面
      }
    },

    // 编辑、增加页面保存方法
    submitForm(editData) {
      this.$refs[editData].validate(valid => {
        if (valid) {
          this.editFormVisible = false
          this.loading = false
          FapiaoSave(this.editForm)
            .then(res => {
              this.editFormVisible = false
              this.loading = false
              console.log(res.success)
              if (res.code==0) {
                this.getdata(this.formInline)
                this.$message({
                  type: 'success',
                  message: '数据保存成功！'
                })
                this.$router.push({ name: 'list' });
              } else {
                this.$message({
                  type: 'info',
                  message: res.msg
                })
              }
            })
            .catch(err => {
              this.editFormVisible = false
              this.loading = false
              this.$message.error('模型保存失败，请稍后再试！')
            })
        } else {
          return false
        }
      })
    },

    // 选中菜单
    changemenu(arr) {
      let change = []
      for (let i = 0; i < arr.length; i++) {
        if (arr[i].checked) {
          change.push(arr[i].id)
        }
      }
      this.checkmenu = change
    },

    // 关闭编辑、增加弹出框
    closeDialog(dialog) {
      if (dialog == 'edit') {
        this.editFormVisible = false
      } else if (dialog == 'perm') {
        this.menuAccessshow = false
      }
    },
    async handleButtonClick(item) {
      this.TagClickList.add(item);
      await this.updateListData();
    },

    async updateListData() {
      const tagIdList = Array.from(this.TagClickList, item => item.id);
      let list = [];
      for (const id of tagIdList) {
        try {
          const res = await ModelgetByModelTagId(id);
          if (res.code !== 200) {
            this.$message({
              type: 'info',
              message: res.msg
            });
            continue;
          }
          list = list.concat(res.data);
        } catch (error) {
          console.error('数据获取失败：', error);
        }
      }
      this.listData = list;
      this.updatePagination(list);
    },

    updatePagination(list) {
      this.pageparm.currentPage = this.formInline.pageNum;
      this.pageparm.pageSize = this.formInline.pageSize;
      this.pageparm.total += list.length;
    },
    handleBeforeUpload(file) {
      console.log(file.name)
      // 创建一个临时的URL来预览图片
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = (e) => {
        console.log(file.name)
        console.log(e.target.result)
        // 将图片的预览URL添加到fileList数组中
        this.fileList.push({ name: file.name, url: e.target.result });
      };
      console.log(this.fileList)
    },
    // 移除图片预览的方法（可选）
    removeImage() {
      // // 移除文件的操作
      // console.log('移除文件: ', file.name);
      // this.fileList[0].name=null
      // this.fileList[0].url=null
      this.fileList.splice(index, 1);
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    handleChange(file) {
      // 在文件上传之前执行的操作，比如检查文件大小、格式等
      // 如果返回false或者返回Promise且被reject，则停止上传
      const isLt200M = file.size / 1024 / 1024 < 200;
      if (!isLt200M) {
        this.$message.error('上传文件大小不能超过 200MB!');
      }
      this.fileList[0].name=file.name
      console.log(isLt200M)
      return isLt200M;
    },
    // 图片上传成功
    imgSuccess(obj) {
    },
    handlePictureCardPreview(file){
      this.dialogImageUrl = file.url;
      this.imgVisible = true;
    },
    handleRemove(file,filelist){
      file=null;
      console.log(file)
      console.log(filelist)
      const findex = this.fileList.map(f => f.name).indexOf(file.name);
      console.log(this.fileList)
      this.fileList =null;
      if (findex > -1) {
        this.fileList.splice(findex, 1);
        filelist.splice(findex, 1);
        // this.$emit("input", this.listToString(this.fileList));
        this.$emit('input', this.fileList)
      }
    },
    fapiaoRequest(obj){
      let formData = new FormData();
      //参数的格式是formData格式的
      formData.append('file', obj.file);
      fapiaoPicUplod(formData).then(res => {
        console.log(res)
        if(res.code==0){
          this.editForm.amount = res.data.amount;
          this.editForm.billnum = res.data.billnum;
        }else {
          this.$message.error('图片上传失败，请稍后再试！')
        }
      });

    },
    handleChildData(dataFromChild) {
      // 父组件接收到子组件传递的数据
      this.editForm.amount = dataFromChild.data.amount;
      this.editForm.billnum = dataFromChild.data.billnum;
    }
  }
}
</script>

<style scoped>
.models-search {
  margin-top: 20px;
}
.userRole {
  width: 100%;
}
</style>
